// components/site-search/index.js
const commonService = require('../../service/common.js');

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  lifetimes:{
    attached: function () {
      // 在组件实例进入页面节点树时执行
      this.getLineList();
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    multiIndex: [0, 0],
    multiArray: [],
    cacheSiteLineList:{}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    bindMultiPickerChange(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        multiIndex: e.detail.value
      })
      let d = {
        site: this.data.multiArray[1][this.data.multiIndex[1]].lineName,
        lineName: this.data.multiArray[0][this.data.multiIndex[0]].lineName,
        lineId: this.data.multiArray[0][this.data.multiIndex[0]].lineId
      }
      this.emitSiteInfo(d);
    },
    bindMultiPickerColumnChange(e) {
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
      if (e.detail.column == 1) return false;
      let key = `multiIndex[${e.detail.column}]`;
      this.setData({
        "multiIndex[0]": e.detail.value,
        "multiIndex[1]": 0
      })
      this.getSiteList();
    },
    getLineList() {
      commonService.getLineList({}).then(res => {
        if (res.resCode == 0) {
          this.setData({
            "multiArray[0]": [{ lineName: "全部", lineId:"ALL"},...res.object]
          });
          this.data.cacheSiteLineList["ALL"] = [{ lineName:""}];
          this.getSiteList();
        }
      }).catch(err => {
      })
    },
    //获取站点列表
    getSiteList(fn = () => { }) {
      let d = {
        lineId: this.data.multiArray[0][this.data.multiIndex[0]].lineId
      }
      if(this.data.cacheSiteLineList[d.lineId]){
        let siteArr = this.data.cacheSiteLineList[d.lineId]
        this.setData({
          "multiArray[1]": siteArr
        });
        fn(siteArr);
        return false;
      }
      commonService.getSiteList(d).then(res => {
        if (res.resCode == 0) {
          let data = res.object.map(v => v.lineName = v.siteName);
          let key = `cacheSiteLineList.${d.lineId}`;
          this.setData({
            "multiArray[1]": res.object,
            [key]:res.object
          });
          //缓存站点 路线
          fn(res.object);
        }
      })
    },
    emitSiteInfo(data = {}){
      const myEventDetail = { ...data } // detail对象，提供给事件监听函数
      const myEventOption = {} // 触发事件的选项
      this.triggerEvent('updateLine', myEventDetail, myEventOption)
    }
  }
})
